import Promise from '../libs/promise.js'
import url from 'url.js'
import net from 'ajax.js'


let functions = {
    loading(f, p) {
        f.then(() => {
            p.setData({
                loadReady: true
            })
        })
    },
    navigateTo(url) {
        return new Promise((resolve, reject) => {
            wx.navigateTo({ url: url, resolve, reject })
        })
    },
    checkNet() {
        return new Promise((resolve, reject) => {
            wx.getNetworkType({
                success: (res) => {
                    resolve(res);
                },
                fail: (res) => {
                    reject(res);
                }
            })
        })
    },
    uploadFile({url, filePath, name, formData}) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: url,
                filePath: filePath,
                name: name,
                header: {
                    'Content-Type': 'application/json'
                },
                formData: formData,
                success: function (res) {
                    resolve(res);
                },
                fail: function (res) {
                    reject(res);
                },
                complete: function () {

                }
            })
        })
    },
    uploadingImg: false,
    getToken(files, f, status, isUpload) {
        let getToken;
        if (this.uploadingImg) {
            this.toast({
                title: "正在上传中...",
                icon: "loading"
            });
            return;
        } else {
            this.uploadingImg = true;
            getToken = net.send(url.getUploadToken);
            !!isUpload && isUpload();
            getToken.then((res) => {
                this.uploadImgs({
                    token: res.info,
                    files: files
                }, f, status)
            }).catch((error) => {
                console.log(error);
                this.uploadingImg = false;
            });
        }
    },
    uploadImgList: [],
    uploadImgs({token, files, index = 0}, f, status) {
        let name = "img" + new Date().getTime().toString() + "_" + index.toString();
        let uploadImg = this.uploadFile({
            url: url.uploadImgUrl,
            filePath: files[index],
            name: 'file',
            formData: {
                token: token,
                key: name
            }
        });
        uploadImg.then((res) => {
            let data = JSON.parse(res.data);
            this.uploadImgList.push(data.key);
            !!status && status(true, index, data.key);
            if (index < (files.length - 1)) {
                index++;
                this.uploadImgs({
                    token: token,
                    files: files,
                    index: index
                }, f, status);
            } else if (index == (files.length - 1)) {
                !!f && f(this.uploadImgList);
                this.uploadingImg = false;
                this.uploadImgList = [];
                // this.toast({
                //     title:"上传成功!"
                // });
            }
        }).catch((error) => {
            console.log(error);
            !!status && status(false, index);
            this.uploadingImg = false;
        });
    },
    toast({title, time = 2000, icon = "success"}) {
        wx.showToast({
            title: title,
            duration: time,
            icon: icon
        })
    },
    chooseImg(count) {
        return new Promise((resolve, reject) => {
            console.log("choose img");
            wx.chooseImage({
                count: count || 9, // 最多可以选择的图片张数，默认9
                sizeType: ['original', 'compressed'], // original 原图，compressed 压缩图，默认二者都有
                sourceType: ['album', 'camera'], // album 从相册选图，camera 使用相机，默认二者都有
                success: function (res) {
                    resolve(res)
                },
                fail: function (res) {
                    console.log(res);
                    reject(res)
                }
            })
        })
    },
    getStorge(key) {
        return new Promise((s, f) => {
            wx.getStorage({
                key: key,
                success: function (res) {
                    s(res);
                },
                fail: function (res) {
                    f(res)
                },
                complete: function () {
                    // complete
                }
            })
        })
    },
    setStorge(key, data) {
        return new Promise((s, f) => {
            wx.setStorage({ key: key, data: data, s, f })
        })
    },
    removeStorge(key) {
        return new Promise((s, f) => {
            wx.removeStorage({
                key: key
            })
        })
    },
    dateFormat(stampStr, format) {
        var date = new Date();
        date.setTime(stampStr * 1000);

        var map = {
            "M": date.getMonth() + 1, //月份 
            "d": date.getDate(), //日 
            "h": date.getHours(), //小时 
            "m": date.getMinutes(), //分 
            "s": date.getSeconds(), //秒 
            "q": Math.floor((date.getMonth() + 3) / 3), //季度 
            "S": date.getMilliseconds() //毫秒 
        };
        format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
            var v = map[t];
            if (v !== undefined) {
                if (all.length > 1) {
                    v = '0' + v;
                    v = v.substr(v.length - 2);
                }
                return v;
            } else if (t === 'y') {
                return (date.getFullYear() + '').substr(4 - all.length);
            }
            return all;
        });
        return format;
    },
    showModal(title, content) {
        return new Promise((resolve, reject) => {
            wx.showModal({
                title: title,
                content: content || "",
                success: (res) => {
                    if (res.confirm) {
                        resolve();
                    }
                }
            })
        })
    },
    showToast(title, icon, d) {
        wx.showToast({
            title: title || '成功',
            icon: icon || 'success',
            duration: d || 1000
        })
    },
    previewImage(url, urls) {
        wx.previewImage({
            current: url, // 当前显示图片的http链接
            urls: urls // 需要预览的图片http链接列表
        })
    }
};

module.exports = functions;